import host.*;

import java.util.ArrayList;
import java.util.Iterator;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class Nodesreader {
	
	public void read(String file) {
		String current = "";
		
		ArrayList<Host> goodguys = new ArrayList<Host>();
		ArrayList<Host> badguys = new ArrayList<Host>();
		
		try {
			boolean good = true;
			boolean contentSet = true;
			Host currentHost = null;

			Reader reader = new FileReader(file);
			XMLInputFactory factory = XMLInputFactory.newInstance();
			XMLEventReader xmlEventReader = factory.createXMLEventReader(reader);

			while (xmlEventReader.hasNext()) {
				XMLEvent event = xmlEventReader.nextEvent();
				
				// start element
				if (event.isStartElement()) {
					StartElement startelement = event.asStartElement();
					current = startelement.getName().getLocalPart();
					
					// iterate attribs
					String port = null;
					Iterator<Attribute> attributes = startelement.getAttributes();
					while (attributes.hasNext()) {
						Attribute attribute = attributes.next();
						// search for port
						if (attribute.getName().toString().equals("Port")) {
							port = attribute.getValue();
						}
					}
					
					// check for node type
					if (current.equals("nodes")) {
						// do nothing
				    } else if (current.equals("GoodGuys")) {
						good = true;
					} else if (current.equals("BadGuys")) {
						good = false;
					} else if (current.equals("IPAddress")) {
						currentHost = new IPAddress(port);
						contentSet = false;
					} else if (current.equals("Hostname")) {
						currentHost = new Hostname(port);
						contentSet = false;
					}
					
					// append to list
					if (currentHost != null)
						if (good)
							goodguys.add(currentHost);
						else
							badguys.add(currentHost);
				} else if (event.isCharacters()) {
					if (currentHost != null) {
						if (!contentSet) 
							currentHost.setContent(event.asCharacters().getData());
						contentSet = true;
					} else {
						current = "";
					}
				}
			}
		}
		catch (FileNotFoundException | XMLStreamException e) {}

		// iterate good guys
		System.out.println("good goys");
		Iterator<Host> hosts = goodguys.iterator();
		while (hosts.hasNext()) {
			System.out.println(hosts.next().toString());
		}
		
		// iterate bad guys
		System.out.println("bad goys");
		hosts = badguys.iterator();
		while (hosts.hasNext()) {
			System.out.println(hosts.next().toString());
		}
	}	
}
